<?php
if(!defined("IICCMS")) exit("Access Denied");
class BaseAction extends Action{
	protected $Config,$sysConfig,$categorys,$module,$moduleid,$mod,$dao,$Type,$Role,$_userid,$_groupid,$_email,$_username ,$forward ,$user_menu,$Urlrule;
    public function _initialize() {
    	//dump(C("SHOW_PAGE_TRACE"));
		 	$this->categorys = F('Category');
			$this->Config = F('Config');
			$this->sysConfig = F('sys.config');
			$this->module = F('Module');
			$this->Role = F('Role');
			$this->Type =F('Type');
			$this->assign('Role',$this->Role);
			$this->assign('Type',$this->Type);
			$this->Urlrule =F('Urlrule');
			$this->assign($this->Config);
			$this->mod= F('Mod');
			$this->moduleid=$this->mod[MODULE_NAME];
			$this->assign('Module',$this->module);
			$this->assign('Categorys',$this->categorys);
			import("@.ORG.Form");
			$this->assign ( 'form',new Form());
			import("@.TagLib.TagLibIic");
    		C('PAGE_LISTROWS',$this->sysConfig['PAGE_LISTROWS']);
			C('URL_M',$this->sysConfig['URL_MODEL']);
			C('URL_M_PATHINFO_DEPR',$this->sysConfig['URL_PATHINFO_DEPR']);
			C('URL_M_HTML_SUFFIX',$this->sysConfig['URL_HTML_SUFFIX']);
			if($_COOKIE['iic_auth']){
				$yourphp_auth_key = sysmd5($this->sysConfig['ADMIN_ACCESS'].$_SERVER['HTTP_USER_AGENT']);
				list($userid,$groupid, $password) = explode("-", authcode($_COOKIE['iic_auth'], 'DECODE', $yourphp_auth_key));
				$this->_userid = $userid;
				$this->_username = $_COOKIE['iic_username'];
				$this->_groupid = $groupid; 
				$this->_email = $_COOKIE['iic_email'];

			}else{
				$this->_groupid = $_COOKIE['iic_groupid']=4;
				$this->_userid =0;
			}
			
			if($_GET['forward'] || $_POST['forward']){	
				$this->forward = $_GET['forward'].$_POST['forward'];
			}else{
				$this->forward =isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] :  $this->Config['site_url'];
			}
			$this->assign('forward',$this->forward);

			foreach((array)$this->module as $r){
				if($r['issearch'])$search_module[$r['name']] = $r['title'];
				if($r['ispost'] && (in_array($this->_groupid,explode(',',$r['postgroup']))))$this->user_menu[$r['id']]=$r;
			}
			$this->assign('search_module',$search_module);
			$this->assign('module_name',MODULE_NAME);
			$this->assign('action_name',ACTION_NAME);
			if(GROUP_NAME=='User'){
				$this->assign('user_menu',$this->user_menu);			
			}
			$this->assign("siteurl",__URL__.'/'.ACTION_NAME);
			$this->assign('ustr','');//date('mW')
	}

    public function index($catid='',$module=''){

		if(empty($catid)) $catid =  intval($_REQUEST['id']);
		$posid =  intval($_REQUEST['posid']);
		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);
		
		
		$cat = $this->categorys[$catid];		
		$bcid = explode(",",$cat['arrparentid']); 
		$bcid = $bcid[1];
		if($bcid == '') $bcid=intval($catid);
		if(empty($module))$module=$cat['module'];
		$this->assign('module_name',$module);
		$left=list_to_tree($this->categorys,"id","parentid",'_son',0);
		foreach ($left as $k=>$v){
			if($v['id']==$bcid){
				$left=$v;
			}
		}
		$this->assign("left",$left);
		$cat['catid']=$cat['id'];	
		unset($cat['id']);
		$this->assign($cat);
		$cat['id']=$catid;
		$this->assign('catid',$catid);
		$this->assign('bcid',$bcid);
		$fields = F($cat['moduleid'].'_Field');
		foreach($fields as $key=>$r){
			$fields[$key]['setup'] =string2array($fields[$key]['setup']);
		}
		$this->assign ( 'fields', $fields); 
		//Page
		if($module=='Page'){
			$module=M('Page');
			$data = $module->find($catid);
			$seo_title = $cat['title'] ? $cat['title'] : $data['title'];
			$this->assign ('seo_title',$seo_title);
			$this->assign ('seo_keywords',$data['keywords']);
			$this->assign ('seo_description',$data['description']);
			unset($data['id']);

			//分页
			$CONTENT_POS = strpos($data['content'], '[page]');
			if($CONTENT_POS !== false) {			
				$urlrule = geturl($cat,'',$this->Urlrule);
				$urlrule[0] =  urldecode($urlrule[0]);
				$urlrule[1] =  urldecode($urlrule[1]);
				$contents = array_filter(explode('[page]',$data['content']));
				$pagenumber = count($contents);
				for($i=1; $i<=$pagenumber; $i++) {
					$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
				} 
				$pages = content_pages($pagenumber,$p, $pageurls);
				//判断[page]出现的位置
				if($CONTENT_POS<7) {
					$data['content'] = $contents[$p];
				} else {
					$data['content'] = $contents[$p-1];
				}
				$this->assign ('pages',$pages);	
			}

			$template = $cat['template_list'] ? $cat['template_list'] : $cat['module'] ;
			$this->assign ($data);		
			$this->display($template);
		}else{
			$seo_title = $cat['title'] ? $cat['title'] : $cat['catname'];
			$this->assign ('seo_title',$seo_title);
			$this->assign ('seo_keywords',$cat['keywords']);
			$this->assign ('seo_description',$cat['description']);
			$where=array();
			$where['status'] =1;
			if($_GET['ctype']){
				$where['ctype']=$_GET['ctype'];
			}
			if($cat['child']){							
				//$where .= " and catid in(".$cat['arrchildid'].")";
				$where['catid']=array('in',$cat['arrchildid']);
			}else{
				$where['catid'] =$catid;
			}
			if($posid){
				$where['posid']=$posid;
			}
			if($module=='Guestbook'){$where['status']=1;}
			if(empty($cat['listtype'])){
				$this->dao= M($module);
				$count = $this->dao->where($where)->count();
				if($_GET['iic']=='demo'){
					dump($this->dao->getLastSql());
				}
				if($count){
					import("@.ORG.ZQPage");
					$listRows =  !empty($cat['pagesize']) ? $cat['pagesize'] : C('PAGE_LISTROWS');
					$page = new ZQPage($count,$listRows,6);
					//$page->urlrule = geturl($cat,'',$this->Urlrule);
					$pages = $page->show();
					$field =  $this->module[$cat['moduleid']]['listfields'];
					$field =  $field ? $field : '*';
					$list = $this->dao->field($field)->where($where)->order('id desc')->limit($page->firstRow.",$listRows")->select();
					$this->assign('pages',$pages);
					if($_GET['iic']=='demo'){
						dump($this->dao->getLastSql());
					}
					$this->assign('list',$list);
				}
				$template_r = '_list';
			}else{
				$template_r = '_index';
			}
			$template = $cat['template_list'] ? $cat['template_list'] : $cat['module'].$template_r;
			$this->display($template);
		}
    }

	public function show($id='',$module=''){
		$p= max(intval($_REQUEST[C('VAR_PAGE')]),1);		
		$id = $id ? $id : intval($_REQUEST['id']);
		$module = $module ? $module : MODULE_NAME;
		$this->assign('module_name',$module);
		$this->dao= M($module);;
		$data = $this->dao->find($id);
		if(empty($data)){
			$this->error('您访问的文档不存在！');
		}
		
		$this->assign("info_id",$id);	
		$catid = $data['catid'];		
		$cat = $this->categorys[$data['catid']];		
		$bcid = explode(",",$cat['arrparentid']); 
		$bcid = $bcid[1]; 
		$this->hits(0);
		if($bcid == '') $bcid=intval($catid);
		$left=list_to_tree($this->categorys,"id","parentid",'_son',0);
		foreach ($left as $k=>$v){
			if($v['id']==$bcid){
				$left=$v;
			}
		}
		$this->assign("left",$left);
		if($cat['readgroup'] && !in_array($this->_groupid,explode(',',$cat['readgroup'])))$this->error (L('add_no_postgroup'));	
		
		if($cat['chargepoint']){
			if($data['userid'] !=$this->_userid){
				$user = M('User');
				$userdata =$user->find($this->_userid);
				if($cat['paytype']==1 && $userdata['point']>=$cat['chargepoint']){
					$chargepointok = $user->setDec('point',"id=".$this->_userid,$cat['chargepoint']);
				}elseif($cat['paytype']==2 && $userdata['amount']>=$cat['chargepoint']){
					$chargepointok = $user->setDec('amount',"id=".$this->_userid,$cat['chargepoint']);
				}else{
					$this->error (L('add_no_postgroup'));
				}				
			}
		}
		$seo_title = $data['title'].'-'.$cat['catname'];
		$this->assign ('seo_title',$seo_title);
		$this->assign ('seo_keywords',$data['keywords']);
		$this->assign ('seo_description',$data['description']);
		$this->assign ( 'fields', F($cat['moduleid'].'_Field') );

		$fields = F($this->mod[$module].'_Field');
		foreach($data as $key=>$c_d){
			$setup='';
			$fields[$key]['setup'] =$setup=string2array($fields[$key]['setup']);
			if($setup['fieldtype']=='varchar' && $fields[$key]['type']!='text'){
				$data[$key.'_old_val'] =$data[$key];
				$data[$key]=fieldoption($fields[$key],$data[$key]);
			}elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){ 
				if(!empty($data[$key])){
					$p_data=explode(':::',$data[$key]);
					$data[$key]=array();
					
					foreach($p_data as $k=>$res){
						$p_data_arr=explode('|',$res);					
						$data[$key][$k]['filepath'] = $p_data_arr[0];
						$data[$key][$k]['filename'] = $p_data_arr[1];
					}				
					unset($p_data);
					unset($p_data_arr);
				}
			}
			unset($setup);
		}
		$this->assign('fields',$fields); 
 
		//手动分页
		$CONTENT_POS = strpos($data['content'], '[page]');
		if($CONTENT_POS !== false) {
			
			$urlrule = geturl($cat,$data,$this->Urlrule);
			$urlrule =  str_replace('%7B%24page%7D','{$page}',$urlrule); 
			$contents = array_filter(explode('[page]',$data['content']));
			$pagenumber = count($contents);
			for($i=1; $i<=$pagenumber; $i++) {
				$pageurls[$i] = str_replace('{$page}',$i,$urlrule);
			} 
			$pages = content_pages($pagenumber,$p, $pageurls);
			//判断[page]出现的位置是否在文章开始
			if($CONTENT_POS<7) {
				$data['content'] = $contents[$p];
			} else {
				$data['content'] = $contents[$p-1];
			}
			$this->assign ('pages',$pages);	
		}

		if(!empty($data['template'])){
			$template = $data['template'];
		}elseif(!empty($cat['template_show'])){
			$template = $cat['template_show'];
		}else{
			$template = $cat['module'].'_show';
		}
		
		$this->assign('catid',$catid);
		//dump($data['pics']);
		$this->assign ($cat);
		$this->assign('bcid',$bcid);
		$this->assign ($data);
        $this->display($template);	 
    }

	public function down(){
		$module = $module ? $module : MODULE_NAME;
		$id = $id ? $id : intval($_REQUEST['id']);
		$this->dao= M($module);
		$filepath = $this->dao->getField('file',"id=".$id);
		$this->dao->setInc('downs',"id=".$id);

		if(strpos($filepath, ':/')) { 
			header("Location: $filepath");
		} else {			
			if(!$filename) $filename = basename($filepath);
			$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
			if(strpos($useragent, 'msie ') !== false) $filename = rawurlencode($filename);
			$filetype = strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
			$filesize = sprintf("%u", filesize($filepath));
			if(ob_get_length() !== false) @ob_end_clean();
			header('Pragma: public');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header('Cache-Control: pre-check=0, post-check=0, max-age=0');
			header('Content-Transfer-Encoding: binary');
			header('Content-Encoding: none');
			header('Content-type: '.$filetype);
			header('Content-Disposition: attachment; filename="'.$filename.'"');
			header('Content-length: '.$filesize);
			readfile($filepath);
		}
		exit;
	}

	public function hits($app='1')
	{
		$module = $module ? $module : MODULE_NAME;
		$id = $id ? $id : intval($_REQUEST['id']);
		$this->dao= M($module);
		$this->dao->setInc('hits',"id=".$id);

		if($module=='Download'){
			$r = $this->dao->find($id);
			if($app=='1'){
				echo '$("#hits").html('.$r['hits'].');$("#downs").html('.$r['downs'].');';
			}
		}else{
			$hits = $this->dao->getField('hits',"id=".$id);
			if($app=='1'){
				echo '$("#hits").html('.$hits.');';
			}
		}
		if($app=='1'){
			exit;
		}
	}
    
	public function insert()
    {
		$module = $module ? $module : MODULE_NAME;
		$model = M($module);
		$fields = F($this->moduleid.'_Field');
		foreach ( $_POST as $key => $val ) {
				$setup='';
				$setup=string2array($fields[$key]['setup']);
				if(!empty($fields[$key]['required']) && empty($_POST[$key])) $this->error (L('do_empty'));
				if($setup['multiple'] || $setup['inputtype']=='checkbox' || $fields[$key]['type']=='checkbox'){
					$_POST[$key] = implode(',',$_POST[$key]);		
				}elseif($fields[$key]['type']=='datetime'){
					$_POST[$key] =strtotime($_POST[$key]);
				}elseif($fields[$key]['type']=='textarea'){
					$_POST[$key]=addslashes($_POST[$key]);
				}elseif($fields[$key]['type']=='images' || $fields[$key]['type']=='files'){
					$name = $key.'_name';
					$arrdata =array();
					foreach($_POST[$key] as $k=>$res){
						 $arrdata[]=$_POST[$key][$k].'|'.$_POST[$name][$k];
					}
					$_POST[$key]=implode(':::',$arrdata);
				}elseif($fields[$key]['type']=='editor'){					
					//自动提取摘要
					if(isset($_POST['add_description']) && $_POST['description'] == '' && isset($_POST['content'])) {
						$content = stripslashes($_POST['content']);
						$description_length = intval($_POST['description_length']);
						$_POST['description'] = str_cut(str_replace(array("\r\n","\t",'[page]','[/page]','&ldquo;','&rdquo;'), '', strip_tags($content)),$description_length);
						$_POST['description'] = addslashes($_POST['description']);
					}
					//自动提取缩略图
					if(isset($_POST['auto_thumb']) && $_POST['thumb'] == '' && isset($_POST['content'])) {
						$content = $content ? $content : stripslashes($_POST['content']);
						$auto_thumb_no = intval($_POST['auto_thumb_no']) * 3;
						if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
							$_POST['thumb'] = $matches[$auto_thumb_no][0];
						}
					}
				}else{
					
				}
		}
		if($fields['createtime']  && empty($_POST['createtime']) )$_POST['createtime'] = time();	
		if($fields['updatetime'])$_POST['updatetime'] = $_POST['createtime'];	
        if($fields['userid'] && empty($_POST['userid']))$_POST['userid'] = $_SESSION['userid'];
		if($fields['username'] && empty($_POST['username']))$_POST['username'] = $_SESSION['username'];
		if($_POST['style_color']) $_POST['style_color'] = 'color:'.$_POST['style_color'];
		if($_POST['style_bold']) $_POST['style_bold'] =  ';font-weight:'.$_POST['style_bold'];
		if($_POST['style_color'] || $_POST['style_bold'] ) $_POST['title_style'] = $_POST['style_color'].$_POST['style_bold'];
 		$_POST['status']='0';
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		$id= $model->add();
		if ($id !==false) {
			if($_POST['aid']) {
				$Attachment =M('Attachment');		
				$aids =  implode(',',$_POST['aid']);
				$data['id']=$id;
				$data['catid']= MODULE_NAME =='Page' ? $id : $_POST['catid'];
				$data['status']= '1';
				$Attachment->where("aid in (".$aids.")")->save($data);
			}

			$data='';
			$cat = $this->categorys[$_POST['catid']];
			$url = geturl($cat,$id,$this->sysConfig);
			$data['id']= $id;
			$data['url']= $url[0];
			$model->save($data);
 
 			if($_POST['moduleid']=='12'){
 				
 			}else{
				$this->assign ( 'jumpUrl', U(MODULE_NAME.'/index') );
 			}
			$this->success (L('add_ok'));
		} else {
			$this->error (L('add_error').': '.$model->getDbError());
		}

    }
    
    /**
	 *展示次数或点击量统计
	 *@date 2010-9-10
	 *@time 上午10:33:46
	 *@param array $arr 资源列表 id 活跃时间 vip开始和结束时间
	 *@param int $click 1:更新点击  2:更新展示
	 */
	protected static function clickorshow($arr=array(), $hits = '1',$model='Tour') {
		//展示次数或点击量统计
		$arc = new Model ( $model );
		$t = time ();
		if ($hits != '1') {
			foreach ( $arr as $v ) {
				$arc->setInc ( 'shownum', "id={$v['id']}", 1 );
			}
		} else {
			$arc->setInc ( 'hits', "id={$arr['id']}", 1 );
			$arc->where("id={$arr['id']}")->setField(array('lasttime'),array($t));
		}
	} //end clickorshow
}
?>